package com.idlewow.character.manager;

import com.alibaba.fastjson.JSON;
import com.idlewow.character.mapper.CharacterMapper;
import com.idlewow.character.model.Character;
import com.idlewow.character.model.CharacterExtraInfo;
import com.idlewow.common.constant.Const;
import com.idlewow.datadict.model.DataDict;
import com.idlewow.datadict.service.DataDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CharacterManager {
    @Autowired
    CharacterMapper characterMapper;

    @Autowired
    DataDictService dataDictService;

    public void createCharacter(String userId, String name, String faction, String race, String job) {
        Character character = new Character();
        character.setUserId(userId);
        character.setName(name);
        character.setFaction(faction);
        character.setRace(race);
        character.setJob(job);
        character.setCreateUser("idlewow");
        CharacterExtraInfo extraInfo = new CharacterExtraInfo();
        extraInfo.setMapId(this.getBornMapId(race).toString());
        character.setExtraInfo(JSON.toJSONString(extraInfo));
        int effected = characterMapper.createCharacter(character);
        if (effected == 0) {
            throw new RuntimeException("sql effected 0 rows");
        }
    }

    public List<Character> getUserCharacters(String userId) {
        return characterMapper.getUserCharacters(userId);
    }

    public Character find(String id) {
        return characterMapper.find(id);
    }

    public Character findByName(String name) {
        return characterMapper.findByName(name);
    }

    public void update(Character character) {
        int effected = characterMapper.update(character);
        if (effected == 0) {
            throw new RuntimeException("sql effected 0 rows");
        }
    }

    private Integer getBornMapId(String race) {
        DataDict dataDict = dataDictService.findByCode(race);
        if (dataDict.getValue().equals("人类")) {
            return Const.BornMap.Human;
        } else if (dataDict.getValue().equals("暗夜精灵")) {
            return Const.BornMap.NightElf;
        } else if (dataDict.getValue().equals("矮人")) {
            return Const.BornMap.Dwarf;
        } else if (dataDict.getValue().equals("侏儒")) {
            return Const.BornMap.Gnome;
        } else if (dataDict.getValue().equals("兽人")) {
            return Const.BornMap.Orc;
        } else if (dataDict.getValue().equals("牛头人")) {
            return Const.BornMap.Tauren;
        } else if (dataDict.getValue().equals("亡灵")) {
            return Const.BornMap.Undead;
        } else if (dataDict.getValue().equals("巨魔")) {
            return Const.BornMap.Troll;
        } else {
            return 0;
        }
    }
}
